import {
  userGetUserInfo,
  getpcindex_new
} from '@/assets/api/indexApi.js'

import {
  getzegotoken_chat
} from '@/assets/api/csjhApi';

export const state = () => ({

  test: 'testvuex',
  // 导航栏选择的下标
  menuIndex: '0',
  // 导航栏数组
  menuList: [{
      name: '问题库',
      index: '1',
      path: '/quizdata',
      hot: true,
      list: [],
    },

    {
      name: '小竹问答',
      index: '2',
      path: '/cswd',
      hot: true,
      list: [{
          name: '普通提问',
          index: '20',
          path: 'cswd-ask',
          params: {},
          query: {}
        },
        {
          name: '专家提问',
          index: '21',
          path: 'cswd-tab-page',
          params: {
            page: '1',
            tab: 'zjwd'
          },
          query: {}
        },
        {
          name: '精选问题',
          index: '22',
          path: 'cswd-tab-page',
          params: {
            page: '1',
            tab: 'jxhd'
          },
          query: {}
        },
        {
          name: '等你来答',
          index: '23',
          path: 'cswd-tab-page',
          params: {
            page: '1',
            tab: 'dnld'
          },
          query: {}
        },
      ],
    },
    {
      name: '税收法规库',
      index: '3',
      path: '/ssfgk/index/0/1',
      list: [],
    },
    {
      name: '会计法规库',
      index: '4',
      path: '/kjfgk/index/0/1',
      list: [],
    },
    {
      name: '小竹企服',
      index: '5',
      path: '/service',
      list: [],
    },
    {
      name: '模板专区',
      index: '60',
      path: '/templates',
      list: [{
          name: '模板首页',
          index: '60',
          path: 'templates',
          params: {},
          query: {},
          noShow: true,
        },
        {
          name: '财税表单',
          index: '61',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '1',
            s_tid: '2',
            page: 1
          },
          query: {}
        },
        {
          name: '规章制度',
          index: '62',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '2',
            s_tid: '6',
            page: 1
          },
          query: {}
        },

        {
          name: '合同范本',
          index: '63',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '3',
            s_tid: '12',
            page: 1
          },
          query: {}
        },
        {
          name: '办公常用',
          index: '64',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '12',
            s_tid: '30',
            page: 1
          },
          query: {}
        },
        {
          name: '毕业季',
          index: '65',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '11',
            s_tid: '9',
            page: 1
          },
          query: {}
        },
        {
          name: '财税干货分享',
          index: '66',
          path: 'templates-modelarea-tid-s_tid-page',
          params: {
            tid: '8',
            s_tid: '36',
            page: 1
          },
          query: {}
        },
      ],
    },

    {
      name: '小竹学院',
      index: '7',
      path: '/school/kzzt',
      list: [{
          name: '考证专题',
          pid: 3,
          index: '70',
          pathName: 'kzzt',
          path: 'school-type',
          params: {
            type: 'kzzt'
          },
          query: {
            index: '70'
          }
        },
        {
          name: '实操视频',
          type: 1,
          index: '71',
          pathName: 'scsp',
          path: 'school-type',
          noShow: true,
          params: {
            type: 'scsp'
          },
          query: {
            index: '71'
          }
        },
        {
          name: '考证题库',
          type: 2,
          index: '72',
          pathName: 'kztk',
          path: 'school-type',
          noShow: true,
          params: {
            type: 'kztk'
          },
          query: {
            index: '72'
          }
        },
        {
          name: '实操课程',
          type: 4,
          pid: 100,
          index: '73',
          pathName: 'sckc',
          path: 'school-type',
          // noShow: true,
          params: {
            type: 'sckc'
          },
          query: {
            index: '73'
          }
        },
        {
          name: '秒懂财税',
          pid: 2,
          index: '74',
          pathName: 'mdcs',
          path: 'school-type',
          params: {
            type: 'mdcs'
          },
          query: {
            index: '74'
          }
        },

        // { name: '财税热点', pid: 1, index: '54', path: '/school' },
      ],
    },
    {
      name: '小竹资讯',
      index: '80',
      path: '/information/rmzx/1',
      list: [{
          name: '热门资讯',
          index: '80',
          path: 'information-type-page',
          params: {
            type: 'rmzx',
            page: '1'
          },
          query: {}
        },
        {
          name: '财政资讯',
          index: '81',
          path: 'information-type-page',
          params: {
            type: 'czzx',
            page: '1'
          },
          query: {}
        },
        {
          name: '考试资讯',
          index: '82',
          path: 'information-type-page',
          params: {
            type: 'kszx',
            page: '1'
          },
          query: {}
        },
        {
          name: '税局稽查',
          index: '83',
          path: 'information-type-page',
          params: {
            type: 'sjjc',
            page: '1'
          },
          query: {}
        },
        {
          name: '财税分享',
          index: '84',
          path: 'information-type-page',
          params: {
            type: 'ggwz',
            page: '1'
          },
          query: {}
        },
      ],
    },
    // {
    //     name: '小竹企服',
    //     index: '8',
    //     path: '/service',
    //     list: [],
    // },
  ],

  // 登录弹窗显示
  loginShow: false,

  // 用户信息
  userInfo: null,

  // 底部是否出现在视窗中
  isFooterShow: false,

  // 浏览记录超过上限显示
  noViewShow: false,

  metaInfo: {},

  zim: null,

  // 未读消息数
  messageCount: {
    commentandlike: 0,
    comment: 0,
    dengnilaida: 0,
    inviteanswer: 0,
    like: 0,
    message: 0,
    question: 0,
    wendahuifu: 0,
    hd_unread: 0,
    xx_unread: 0
  },

  // 小竹问答热门标签
  hotTags: [],

  // 首页数据
  indexRes: null,

  // 首页数据
  indexHotSearch: null,

  // 会话列表
  conversationList: [],

  // zim是否登录
  zimStatus: false,

  goeasyObj: null,

  
  AppNavShow: true

})

export const getters = {
  menuIndex: (state) => state.menuIndex,
  menuList: (state) => state.menuList,
  schoolList: (state) => state.menuList[6].list,

  loginShow: (state) => state.loginShow,
  userInfo: (state) => state.userInfo,

  isFooterShow: (state) => state.isFooterShow,

  noViewShow: (state) => state.noViewShow,
  AppNavShow: (state) => state.AppNavShow,
}

export const mutations = {
  set_AppNavShow(state, AppNavShow) {
    state.AppNavShow = AppNavShow
  },
  setmenuIndex(state, menuIndex) {
    state.menuIndex = menuIndex
  },
  removeMenuIndex(state) {
    state.menuIndex = null
  },
  setloginShow(state, loginShow) {
    state.loginShow = loginShow
  },

  setuserInfo(state, userInfo) {
    state.userInfo = userInfo
  },

  setisFooterShow(state, isFooterShow) {
    state.isFooterShow = isFooterShow
  },

  setNoViewShow(state, noViewShow) {
    state.noViewShow = noViewShow
  },

  set_metaInfo(state, data) {
    state.metaInfo = data
  },

  set_zim(state, data) {
    console.log(data)
    state.zim = data
  },

  set_messageCount(state, data) {
    state.messageCount.commentandlike = parseInt(data.commentandlike)
    state.messageCount.message = parseInt(data.message)
    state.messageCount.dengnilaida = parseInt(data.dengnilaida)
    state.messageCount.comment = parseInt(data.comment)
    state.messageCount.like = parseInt(data.like)
    state.messageCount.inviteanswer = parseInt(data.inviteanswer)
    state.messageCount.question = parseInt(data.question)
    state.messageCount.wendahuifu = parseInt(data.wendahuifu)

  },
  set_messageCount2(state, data) {
    if (data.xx_unread || data.xx_unread === 0)
      state.messageCount.xx_unread = parseInt(data.xx_unread)
    if (data.hd_unread || data.hd_unread === 0)
      state.messageCount.hd_unread = parseInt(data.hd_unread)
  },

  set_hotTags(state, data) {
    state.hotTags = data
  },

  set_indexRes(state, data) {
    state.indexRes = data
  },

  set_conversationList(state, query) {
    let data = query.conversationList
    for (let item of data) {
      if (item.lastMessage) {
        let extendedData = JSON.parse(item.lastMessage.extendedData)
        if (extendedData.quiz_id) {
          query.zim.deleteConversation(item.conversationID, 0, {
            isAlsoDeleteServerConversation: true
          })
        }
      }
    }
    state.conversationList = data.sort((obj1, obj2) => {
      return obj2.orderKey - obj1.orderKey;
    })
  },

  set_zimStatus(state, data) {
    state.zimStatus = data
  },

  // 更新会话列表，接受一个数组
  updata_ConversationList(state, conversationList) {

    // state.conversationList = conversationList
    state.conversationList = JSON.parse(JSON.stringify(conversationList))

  },

  set_indexHotSearch(state, data) {
    state.indexHotSearch = {}
    for (let i = 0; i < data.length; i++) {
      data[i].type
      switch (data[i].type) {
        case 1:
          state.indexHotSearch['1'] = data[i].content
          break;
        case 2:
          state.indexHotSearch['3'] = data[i].content
          break;
        case 3:
          state.indexHotSearch['4'] = data[i].content
          break;
        case 4:
          state.indexHotSearch['0'] = data[i].content
          break;
        case 5:
          state.indexHotSearch['5'] = data[i].content
          break;
        case 6:
          state.indexHotSearch['6'] = data[i].content
          break;
        case 7:
          state.indexHotSearch['7'] = data[i].content
          break;
        case 8:
          state.indexHotSearch['2'] = data[i].content
          break;
      }

    }
  },

  set_goeasyObj(state, data) {
    state.goeasyObj = data
  },

  // 不可以看实操视频和考证题库的
  noLookShool(state, data) {
    state.menuList[6].list[1].noShow = true
    state.menuList[6].list[2].noShow = true
    // state.menuList[6].list[3].noShow = true
  },

  // 可以看实操视频和考证题库的
  yesLookShool(state, data) {
    // state.menuList[6].list[1].noShow = false
    // state.menuList[6].list[2].noShow = false
  },
}

export const actions = {
  // 获取用户信息
  async getUserInfo(context) {
    if (localStorage.getItem('userInfo')) {
      try {
        context.commit('setuserInfo', JSON.parse(localStorage.getItem('userInfo')))
      } catch (error) {}
    }
    let token = localStorage.getItem('token')
    if (token) {
      const res = await userGetUserInfo(null)
      if (res.code == 1) {
        localStorage.setItem('userInfo', JSON.stringify(res.data))
        context.commit('setuserInfo', res.data)
      } else {
        localStorage.removeItem('userInfo')
        context.commit('setuserInfo', null)

      }
    } else {
      context.commit('setuserInfo', null)
      localStorage.removeItem('userInfo')
    }
  },
  async getUserInfo2(context) {
    return new Promise(async (resolve, reject) => {
      if (context.state.userInfo) {
        resolve(context.state.userInfo)
      } else {
        let token = localStorage.getItem('token')
        if (token) {
          const res = await userGetUserInfo(null)
          if (res.code == 1) {
            context.commit('setuserInfo', res.data)
            resolve(res.data)
          } else {
            context.commit('setuserInfo', null)
            reject(null)
          }
        } else {
          context.commit('setuserInfo', null)
          reject(null)
        }
      }

    })
  },
  // 
  createZIM(context) {
    return new Promise(async (resolve, reject) => {
      resolve('zim')
    })
  },

  ZIMLogin(context, zim) {

    return new Promise(async (resolve, reject) => {
      let res = {
        data: {},
      };
      if (localStorage.getItem("zegoToken")) {
        res.data.token = localStorage.getItem("zegoToken");
        res.code = 1;
      } else {
        res = await getzegotoken_chat({
          user_id: context.state.userInfo.id,
        });
      }

      if (res.code == 1) {
        zim.login({
              userID: context.state.userInfo.id + "",
              userName: context.state.userInfo.nickname,
            },
            res.data.token
          )
          .then(function () {


            console.log('zim登录成功')
            context.commit('set_zimStatus', true)

            try {
              let avatar = context.state.userInfo.is_server == 1 ? context.state.userInfo.service_info.logo : context.state.userInfo.avatar
              let userName = context.state.userInfo.is_server == 1 ? context.state.userInfo.service_info.name : context.state.userInfo.nickname
              if (userName)
                zim.updateUserName(userName)
              if (avatar)
                zim.updateUserAvatarUrl(avatar).then(function ({
                  userAvatarUrl
                }) {
                  // 操作成功
                  console.log('换头像操作成功', userAvatarUrl)
                })
                .catch(function (err) {
                  // 操作失败
                  console.log('换头像操作失败')
                });
            } catch (error) {
              console.log(error)
            }

            resolve(zim)

          })
          .catch(function (err) {
            // setTimeout(() => {
            //   localStorage.removeItem("zegoToken");
            //   context.dispatch('ZIMLogin')
            // }, 100);
            // context.state.zim.logout()
          });
      }

    })

  },

  queryConversationList(context, zim) {
    return new Promise(async (resolve, reject) => {
      zim
        .queryConversationList({
          // 会话锚点，传空则代表从最新开始查询
          nextConversation: null,
          count: 20
        })
        .then(function ({
          conversationList
        }) {
          console.log('会话列表---', conversationList)
          // 查询成功，开发者需要保存和维护数组内的会话对象
          context.commit('set_conversationList', {
            conversationList: conversationList,
            zim: zim
          })

          resolve(conversationList)
        })
        .catch(function (err) {
          // 查询失败
          reject(err)
        });
    })

  },



  async getIndexRes({
    commit,
    state
  }, params) {
    const res = await getpcindex_new(params)
    if (res.code == 1) {
      commit('set_indexRes', res.data)
    }
  },

}
